
import debounce from "lodash.debounce";
import { renameObjectKeys } from "../functions";

let primaryKeyObj = null;
let isModification = false;

// 获取查询混合
export function getQueryOptions(config = {}) {
    let { apiurl, params, paginable, resultProperty = 'tableData', fnAfterQuery, queryOnCreation = true } = config;

    const data = { queryString: '' };

    if (paginable) {
        data.currentPage = 1;
        data.pageSize = 10;
        data.total = 0;
    }

    function query() {
        // 发送的参数
        let $params = {};
        this[resultProperty] = [];

        for (const key in params) {
            const val = params[key];

            $params[val in this ? this[val] : val] = key in this ? this[key] : key;

        }
        // for (const name in params) {
        //     const param = params[name];

        //     if (isNaN(+name)) {
        //         _params[param in this ? this[param] : param] = this[name];
        //     } else {

        //         if (typeof param === 'string') {
        //             _params[param] = this[param];
        //         } else {
        //             for (const _name in param) {
        //                 _params[param[_name] in this ? this[param[_name]] : param[_name]] = this[_name];
        //             }
        //         }

        //     }
        // }

        if (paginable) {
            $params.pageSize = this.pageSize;
            $params.pageCurrent = this.currentPage;
        }

        this.$get(apiurl, $params).then(res => {

            // 回调函数
            if (typeof fnAfterQuery === 'function') {
                if (!fnAfterQuery.call(this, paginable ? res.records : res)) {
                    return;
                };
            } else if (typeof fnAfterQuery === 'string') {
                if (this[fnAfterQuery](paginable ? res.records : res)) {
                    return;
                };
            }

            if (paginable) {
                this[resultProperty] = Object.freeze(res.records);
                this.total = res.total;
            } else {
                this[resultProperty] = Object.freeze(res);
            }
        })
    }

    let options = {
        data() { return data },
        methods: { query },
        watch: {
            queryString: debounce(function () {
                this.currentPage = 1;
                this.query();
            }, 600)
        }
    }

    if (queryOnCreation) {
        options.created = query;
    }

    return options;
}

// 获取删除混合
export function getDeletionOptions(config = {}) {
    let { apiurl, batchable = true, refreshMethod = 'query', primaryKey, params, requestMethod = '$$delete' } = config;

    const data = {}

    const computed = {}

    const methods = {
        _delete(id) {
            if (!params) return;

            let $params = {
                [params]: typeof id === 'number' ? id : this.batchSelected.toString()
            }

            // if (typeof id === 'number') {
            //     params[name] = id;
            // } else if (idArray && idArray.length) {
            //     params[name] = idArray.toString();
            // } else return;

            this.$confirm('是否确定删除数据', '删除提示', {
                showClose: false,
                closeOnClickModal: false,
                type: 'error',
            }).then(() => {
                this[requestMethod](apiurl, $params).then(this[refreshMethod])

            }).catch(function () { });
        }
    }


    // 可批量必须存在主键
    if (batchable && primaryKey) {

        data.batchSelected = [];

        computed.isBatchButtonDisabled = function () {
            return !this.batchSelected.length;
        }

        methods.handleSelect = function (selectedRows) {
            this.batchSelected = selectedRows.map(row => row[primaryKey]);
        }
    }

    return {
        data() { return data },
        methods,
        computed
    }
}

// 获取修改混合
export function getModificationOptions(config) {
    let { primaryKey, formDataProperty = 'formData', dialogDisplayProperty = 'visible', formDataKeyMapping, fnBeforeOpening } = config || {};

    function modify(row) {
        let form = this[formDataProperty], _row = { ...row };
        renameObjectKeys(_row, formDataKeyMapping);

        for (const key in _row) {
            if (key in form) {
                form[key] = _row[key];
            }
        }

        isModification = true;
        primaryKeyObj = {
            [primaryKey]: row[primaryKey]
        }

        if (typeof fnBeforeOpening === 'function') {
            fnBeforeOpening.call(this);
            return;
        } else if (typeof fnBeforeOpening === 'string') {
            this[fnBeforeOpening]();
            return;
        }

        this[dialogDisplayProperty] = true;
    }

    return {
        methods: { modify }
    }
}

// 获取添加混合
export function getAdditionOptions(config) {
    let { apiurl, additionApiurl, modificationApiurl, fnBeforeOpening, fnBeforeSaving, fnAfterSaving, formDialogDisplayProperty = 'visible', refreshMethod = 'query', formDataProperty = 'formData' } = config || {};

    if (apiurl) {
        additionApiurl = apiurl;
    }

    let methods = {
        // 添加操作
        add() {
            isModification = false;

            if ('formAction' in this) {
                this.formAction = 'add';
            }

            if (typeof fnBeforeOpening === 'function') {
                fnBeforeOpening.call(this);
                return;
            } else if (typeof fnBeforeOpening === 'string') {
                this[fnBeforeOpening]();
                return;
            }

            this[formDialogDisplayProperty] = true;
        },

        // 表单提交（保存）
        save() {
            let data = isModification ? { ...primaryKeyObj, ...this[formDataProperty] } : { ...this[formDataProperty] };

            if (typeof fnBeforeSaving === 'function') {
                if (!fnBeforeSaving.call(this, data, isModification)) return;
            } else if (typeof fnBeforeSaving === 'string') {
                if (!this[fnBeforeSaving](data, isModification)) return;
            }

            this.$put(isModification ? modificationApiurl : additionApiurl, data).then(() => {

                this[formDialogDisplayProperty] = false;
                this[refreshMethod]();

                if (typeof fnAfterSaving === 'function') {
                    fnAfterSaving.call(this)
                } else if (typeof fnAfterSaving === 'string') {
                    this[fnAfterSaving]();
                }
            })

        }
    }

    return {
        methods,
        computed: {
            dialogTitle() {
                return isModification ? '修改协议' : '添加协议';
            }
        }
    }
}